<?php
use Phalcon\Mvc\View;

class AssetController extends ControllerBase
{
    public $currPluginRoot; //当前插件的根目录
    public $createExt = ['.css', '.js']; //文件扩展名
    public $max       = 100;

    public function initialize()
    {
        parent::initialize();
        $this->currPluginRoot = BASE_PATH . '/_site/' . $this->siteid . '/asset/';
        $this->tbl            = $this->currPluginRoot . 'config.json';
    }

    public function indexAction()
    {
        $path = '/';
        $this->assets->addJs("/static/asset/js/asset.js");
        $this->view->setVars(
            [
                'path'      => $path,
                'dir'       => $file,
                'crumbData' => [
                    [
                        'name' => $this->view->currentSite[$this->siteid]['name'],
                        'url'  => '/' . $this->siteid . '/dir/index',
                    ],
                    [
                        'name' => '资源管理器',
                        'url'  => 'javascript:;',
                        'curr' => 1,
                    ],
                ],
            ]
        );
    }

    /**
     * 删除
     */
    public function deleteAction()
    {
        //获取删除的id
        $ids = $this->request->getPost('ids');

        $tmp = []; //存放删除成功的id

        //循环删除文件
        foreach ($ids as $key => $value) {
            $ret = unlink($this->currPluginRoot . $value);
            if ($ret) {
                $tmp[] = md5($value);
            }
        }

        //循环清理数据表
        if (empty($tmp)) {
            $json = ['code' => 1, 'msg' => '文件不存在或者权限不够，请检查'];
        } else {
            $json = ['code' => 0, 'msg' => '总计删除 ' . count($tmp) . ' 条记录', 'data' => $tmp];
        }

        $this->response->setJsonContent($json);
        return $this->response;
    }

    /**
     * 编辑
     */
    public function editAction()
    {
        $this->tag->setTitle('编辑资源');

        $fn  = $this->request->getQuery('fn', ['trim', 'string']);
        $ext = substr(strrchr($fn, '.'), 1);

        if (!in_array($ext, ['css', 'js', 'html', 'volt'])) {
            $this->dispatcher->forward(array(
                "controller" => "index",
                "action"     => "error",
                "params"     => array('message' => '暂不支持对该文件格式的编辑'),
            ));
        }

        $path = $this->currPluginRoot . $fn;
        if (!file_exists($path)) {
            $this->dispatcher->forward(array(
                "controller" => "index",
                "action"     => "error",
                "params"     => array('message' => '资源不存在'),
            ));
        }

        $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
        $this->assets->addCss("/codemirror/codemirror.css");
        $this->assets->addCss("/static/asset/css/asset.css");
        $this->assets->addJs("/codemirror/codemirror.js");
        if ($ext == 'css') {
            $this->assets->addJs("/codemirror/css.js");
            $this->view->mode = 'text/css';
        } elseif ($ext == 'js') {
            $this->assets->addJs("/codemirror/javascript.js");
            $this->view->mode = 'text/javascript';
        } elseif (in_array($ext, ['volt', 'html'])) {
            $this->assets->addJs("/codemirror/htmlmixed.js");
            $this->view->mode = 'htmlmixed';
        }
        $this->assets->addJs("/static/asset/js/asset.js");
        $content             = file_get_contents($path);
        $this->view->fn      = $fn;
        $this->view->content = $content;

    }

    /**
     * 创建
     */
    public function createAction()
    {
        $tbl = [];
        if (file_exists($this->tbl)) {
            $string = file_get_contents($this->tbl);
            $tbl    = json_decode($string, true);
            if (count($tbl) >= $this->max) {
                $json = ['code' => 6, 'msg' => '已经达到了创建允许的最大值'];
                $this->response->setJsonContent($json);
                return $this->response;
            }
        }
        //获取数据
        $ext  = $this->request->getPost('ext', ['trim', 'string']);
        $path = ltrim($this->request->getPost('path', ['trim', 'string']), '/');

        if (empty($ext) || empty($path)) {
            $json = ['code' => 2, 'msg' => '参数不足'];
        } else {

            if (!in_array($ext, $this->createExt)) {
                $json = ['code' => 7, 'msg' => '文件格式不被允许'];
                $this->response->setJsonContent($json);
                return $this->response;
            }
            //对存储路径进行识别
            $pattern = '/^[0-9A-Za-z\/\-\_]{5,50}$/';
            if (!preg_match($pattern, $path)) {
                $json = ['code' => 3, 'msg' => '存储路径只接受5-20位的字母,数字,下划线,分割线,斜杠任意组合'];
                $this->response->setJsonContent($json);
                return $this->response;
            }

            //如果设定了斜杠，则检查斜杠
            if (strpos($path, '/')) {
                //最多深度为5
                if (count(explode('/', $path)) > 5) {
                    $json = ['code' => 5, 'msg' => '目录创建深度为5级'];
                    $this->response->setJsonContent($json);
                    return $this->response;
                }

                //创建目录
                $dir = substr($path, 0, strrpos($path, '/'));
                $dir = $this->currPluginRoot . $dir;
                if (!is_dir($dir)) {
                    $ret = mkdir($dir, 0777, true);
                    //第三个参数为true即可以创建多极目录
                    if (!$ret) {
                        $json = ['code' => 4, 'msg' => '目录创建失败'];
                        $this->response->setJsonContent($json);
                        return $this->response;
                    }
                }
            }

            $file = $this->currPluginRoot . $path . $ext;
            //验证文件是否存在
            if (file_exists($file)) {
                $json = ['code' => 1, 'msg' => '文件已经存在'];
            } else {
                if ($ext == '.css') {
                    $content = "\/**这是一个css文件**\/";
                } elseif ($ext == '.js') {
                    $content = "\/**这是一个js文件**\/";
                }
                file_put_contents($file, $content);
                $tbl[md5($path . $ext)] = ['path' => $path . $ext];
                $string                 = json_encode($tbl, JSON_UNESCAPED_UNICODE);
                file_put_contents($this->tbl, $string);
                $json = ['code' => 0, 'msg' => null];
            }
        }

        $this->response->setJsonContent($json);
        return $this->response;
    }

    public function rowsAction()
    {
        $page     = $this->request->getQuery('page', ['trim', 'int']);
        $rows     = Common::getDirContent($this->currPluginRoot);
        $pagesize = 20;
        $count    = count($rows); //总条数
        $total    = ceil($count / $pagesize);
        $start    = ($page - 1) * $pagesize; //偏移量，当前页-1乘以每页显示条数
        $rows     = array_slice($rows, $start, $pagesize);
        foreach ($rows as $key => &$value) {
            $value['md5']      = md5($value['name']);
            $ext               = substr(strrchr($value['name'], '.'), 1);
            $value['editable'] = in_array($ext, ['css', 'js', 'html', 'volt']) ? 1 : 0;
        }
        $this->response->setJsonContent(['data' => $rows, 'total' => $total, 'pagesize' => $pagesize, 'current' => count($rows)]);
        return $this->response;
    }

    public function uploaderAction()
    {
        $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
    }

    /**
     * 编辑保存
     */
    public function saveAction()
    {
        $fn      = $this->request->getPost('fn', ['trim', 'string']);
        $content = $this->request->getPost('content', "trim");
        $path    = $this->currPluginRoot . $fn;
        if (!is_writable($path)) {
            $json = ['code' => 1, 'msg' => '权限不足，禁止访问。'];
        } else {
            $info = file_put_contents($path, $content);
            $json = ['code' => 0, 'msg' => null];
        }

        $this->response->setJsonContent($json);
        return $this->response;
    }

    public function backendAction()
    {
        header('Content-type:application/json;charset=utf-8');

        try {
            if (
                !isset($_FILES['file']['error']) ||
                is_array($_FILES['file']['error'])
            ) {
                throw new RuntimeException('Invalid parameters.');
            }

            switch ($_FILES['file']['error']) {
                case UPLOAD_ERR_OK:
                    break;
                case UPLOAD_ERR_NO_FILE:
                    throw new RuntimeException('No file sent.');
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    throw new RuntimeException('Exceeded filesize limit.');
                default:
                    throw new RuntimeException('Unknown errors.');
            }

            $filepath = sprintf(BASE_PATH . '/_site/' . $this->siteid . '/asset/%s', $_FILES['file']['name']);

            if (!move_uploaded_file(
                $_FILES['file']['tmp_name'],
                $filepath
            )) {
                throw new RuntimeException('Failed to move uploaded file.');
            }

            // All good, send the response
            echo json_encode([
                'status' => 'ok',
                'path'   => $filepath,
            ]);

        } catch (RuntimeException $e) {
            // Something went wrong, send the err message as JSON
            http_response_code(400);

            echo json_encode([
                'status'  => 'error',
                'message' => $e->getMessage(),
            ]);
        }
        die;
    }
}
